<?php
namespace services;

use Yii;
use yii\base\Component;
use hianto2o\db\Query;
use yii\data\Pagination;
use heihei\base\UserHintExitException;

/**
 * 服务层基础类
 *
 * @author dejin <ldj@hianto2o.com>
 */
class Service extends Component
{
    public static function toListPage($query, $params = null, $db = null){
        $countQuery = clone $query;
        $pages = new Pagination([
            'totalCount' => $countQuery->count('1', $db), 
            'params'=>$params,
            'defaultPageSize'=>20,
            'pageSizeParam'=>'pagesize'
        ]);        

        $list = $query          
            ->offset($pages->offset)
            ->limit($pages->limit)
            ->all($db);
        $pageParam = $pages->pageParam;
        $page = isset($params[$pageParam]) && is_scalar($params[$pageParam]) ? $params[$pageParam] : 1;
        $pagination = array(
            'page' => $page,
            'pageCount' => $pages->getPageCount(),
            'totalCount' => 0 + $pages->totalCount,
            'pageSize' => $pages->getPageSize(),
            'offset' => $pages->offset,
            'limit' => $pages->limit,
            'isLastPage' => $page >= $pages->getPageCount() ? 1 : 0
        );
        $data = array('list'=>$list,'pagination'=>$pagination);
        return $data;
    }

    /**
     * 失败输出
     */
    public static function fail($message){
        throw new UserHintExitException($message);
    }

    /**
     * 获取环境
     */
    public static function getEnvironmentType(){
        $env = isset($_SERVER['RUN_YILING_ENV']) ? $_SERVER['RUN_YILING_ENV'] : 'prod';
        return in_array($env, ['dev','pre']) ? $env : 'prod';
    }

}
